from flask import Blueprint,request,make_response,jsonify,redirect
from flask_restful import Resource,Api
from utils.Myredis import r
from utils.captcha.captcha import captcha
from utils.Myredis import r
import json
from utils.comm import send_message
import random
from application.models.users.user import *
from application.models.users.user import db
from db import db
import time
from utils.Myjwt import myjwt
import functools,time
goods_blue=Blueprint("goods",__name__)
api=Api(goods_blue)

# 获取类别
# @goods_blue.route("/gettype")
def gettype():
    sql = "select * from  ctype"
    res = db.findAll(sql)
    return res
    # res=r.get_str("typelist")
    # if res:
    #     res=json.loads(res)
    #     print("缓存")
    # else:
    #     types=Ctype.query.all()
    #     lst=[]
    #     for i in types:
    #         lst.append({
    #             "id": i.id,
    #             "name": i.name
    #         })
    #     # r.add_str("typelist",json.dumps(lst))
    #     # print("数据库")
    #     return jsonify({"code":200,"msg":"ok","lst":lst})
# 获取标签
# @goods_blue.route("/gettag")
def gettag():
    sql = 'select * from tags'
    res = db.findAll(sql)
    return res
    # res=r.get_str("taglist")
    # if res:
    #     res=json.loads(res)
    #     print("缓存")
    # else:
    #     res=Tags.query.all()
    #     lst=[]
    #     for i in res:
    #         lst.append({
    #             "id":i.id,
    #             "status":i.status,
    #             "name":i.name
    #         })
    #     # r.add_str("taglist",json.dumps(lst))
    #     return jsonify({"code":200,"msg":"ok","lst":lst})
# 获取课程信息
def getcourse(page):
    page_size=2
    # 查询缓存 如果存在直接返回
    key="home"+str(page)
    courselist=r.get_str(key)
    if courselist:
        courselist=json.loads(courselist)
    else:
        # 获取指定页数据
        start = (int(page) - 1)* page_size
        print("ttttttt",type(start))
        # 并发访问同时操作数据库 解决方案分布式锁
        flag=r.str_setnx(key+"setnx",1)
        if flag==True:
            sql1 = "select * from course limit %d,%d" % (int(start), page_size)
            lst=db.findAll(sql1)
            # 存在redis  decimal float  datetime 时间日期类型
            courselist=[]
            for i in lst:
                i["create_time"]=datetime.datetime.strftime(i["create_time"],"%Y-%m-%d %H:%M:%S")
                courselist.append(i)
            r.add_str(key,json.dumps(courselist))
            # 释放锁
            r.del_key(key+"setnx")
    sql="select count(id) as t from course"
    res=db.findone(sql)
    total=res["tcount"]
    # 指定每页显示多少条
    return courselist,total,page_size
#获取首页课程分类及课程信息
@goods_blue.route("/home")
def home():
    # 获取当前页
    page=request.args.get("page")
    # 获取类型
    types=gettype()
    # 获取标签
    tags=gettag()
    # 获取课程
    courselist,total,page_size=getcourse(page)
    return jsonify({"code":200,'typelist':types,"taglist":tags,"clist":courselist,"total":total,"page_size":page_size})
# 多条件查询
# 获取首页课程分类及课程信息
@goods_blue.route("/getHomeCourse")
def getHomeGourse1():
    # 获取类型
    typelist = gettype()
    # 获取标签
    taglist = gettag()

    # 获取当前页面
    page = request.args.get("page")
    # 获取查询条件
    tagid = request.args.get("tagid")
    typeid=request.args.get("type")
    is_publish=request.args.get("is_publish")
    orderbyid=request.args.get("orderbyid")
    where=" "
    if int(typeid)>0:
        where=where+"and c.ctype="+typeid

    if int(is_publish)>0:
        where=where+" and c.is_publish=" +is_publish
    if int(tagid) > 0:
        tsql = "select count(c.id) as tcount from course as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid="+tagid
        sql = "select * from course as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid="+tagid
    else:
        sql = "select * from course as c  where 1=1"
        tsql = "select count(c.id) as  tcount from course as c  where 1=1"
    if where:
        sql=sql+" "+where
        tsql=tsql+" "+ where

    if int(orderbyid)>0:
        if int(orderbyid)==1:
            # 等于1倒叙
            sql=sql+" order by c.id desc"
        else:
            # 等于2按点击数
            sql= sql+" order by c.views desc"
    # 查询总共有多少条
    res = db.findone(tsql)
    total = res['tcount']
    page_size = 2
    start = (int(page) - 1)*page_size
    sql = sql + " limit %d,%d" % (start, page_size)
    courselist = db.findAll(sql)
    print(sql)
    return jsonify({"code": 200, "typelist": typelist, 'taglist': taglist, 'courselist': courselist, "total": total, "page_size": page_size})
# 课程详情页面
@goods_blue.route("/detail")
def detail():
    id=request.args.get("id")
    key="course"+str(id)
    jkey="jie"+str(id)
    # r.del_key(key)
    # r.del_key(jkey)
    # 课程信息
    course=r.get_str(key)
    # 如果课程存在 章节就存在
    if course:
        # 缓存
        jie=r.get_str(jkey)
        return jsonify({"code":200,"clist":json.loads(course),"slist":json.loads(jie)})
    else:  #不存在访问数据库
        sql="select c.id,j.id as jid ,c.descrip,j.url,j.courseid,j.name,c.tcount,c.ctype from course as c inner join jie as j on c.id=j.courseid where c.id=%d"%(int(id))
        res=db.findAll(sql)
        jie=[]
        # 课程下的所有章节
        for i in res:
            jie.append({
                "id":i["id"],
                "name":i["name"],
                "url":i["url"],
                "courseid":i["courseid"],
                "ctype":i["ctype"]
            })
        # 课程信息
        clist=[{"id":res[0]["id"],"tcount":res[0]["tcount"],"url":res[0]["url"],"descrip":res[0]["descrip"]}]
        r.add_str(key,json.dumps(jie))
        print(jie,clist,">>>>")
        r.add_str(jkey,json.dumps(jie))
        return jsonify({"code":200,"jie":jie,"clist":clist})
@goods_blue.route("/getVideo")
def getVideo():
    courseid=request.args.get("courseid")
    userid=request.args.get("userid")
    id=request.args.get("id")
    sql="select level from user where id=%d"%(int(userid))
    user=db.findone(sql)
    # 通过课程id查询课程类型
    key="course"+str(courseid)
    course=r.get_str(key)
    if course:
        course=json.loads(course)
        print("rrrrrrr",course)
        for i in course:
            print(i)
            ctype=i['ctype']
            if int(ctype)==2:
                # 会员可看
                for j in user:
                    user = j["level"]
                    if int(user["ctype"])!=2:
                        return jsonify({"code":401,"msg":"此用户无权观看"})
            # 课程类型为3时需要购买
            if int(ctype)==3:
                sql1="select * from vipuser_course where userid=%d and courseid=%d"%(int(userid),int(courseid))
                res1=db.findone(sql1)
                if not res1:
                    return jsonify({"code":401,"msg":"此课程需要购买"})
            # 返回课程的url 课程下的所有章节
            jkey="jie"+str(courseid)  #课程id
            jies=json.loads(r.get_str(jkey))
            for i in jies:
                if int(i["id"])==int(id):
                    url=i["url"]
                    return jsonify({"code":200,"url":url})
    else:
        return jsonify({"code":10010})
# 加入购物车
from utils.Myredis import r
@goods_blue.route("/addcart",methods=["POST"])
def addcart():
        # cid=request.json.get("cid")
        # userid=request.json.get("userid")
        data=json.loads(request.data)
        userid=data["userid"]
        cid=data["goodsid"]
        # 调用redis hash  add进行添加
        key="mycart"+str(userid)
        r.hash_add(key,cid,1)
        return jsonify({"code":200,"msg":"加入购物车成功"})
# 我的购物车
@goods_blue.route("/getcourse")
def getcourse():
    userid=request.args.get("userid")
    key="mycart"+str(userid)
    res=r.hash_getall(key)
    for i,j in res.items():
        goodsid=i.decode()
        sql="select id,name,url,views,tcount from course where id=%d"%(int(goodsid))
        res=db.findone(sql)
    return jsonify({"code":200,"msg":"ok","list":res})
from utils.comm import get_ali_object
@goods_blue.route("/pay",methods=["POST"])
def pay():
    data=json.loads(request.data)
    userid=data["userid"]
    courseid=int(data["courseid"])
    sum=0
    sql="select * from course where id=%d"%courseid
    res=db.findone(sql)
    sum+=float(res["views"])
    usql="insert into vipuser_course(courseid, userid) values(%d,%d)"%(int(courseid),int(userid))
    db.add(usql)
    # 查询课程的信息
    csql="select * from course where id=%d"%courseid
    course=db.findone(csql)
    name=course["name"]
    url=course["url"]
    # 订单号
    number=str(int(time.time()))+str(userid)+str(random.randint(1000,9999))
    create_time=datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
    update_time=datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
    status=2
    isql="insert into orders(create_time,update_time,userid, courseid, order_num, tmoney,status) values ('%s','%s','%s','%s','%s','%f','%s')"%(str(create_time),str(update_time),userid,courseid,number,int(sum),status)
    db.add(isql)
    db.commit()
    # 支付
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(userid) + "购买课程",  # 商品简单描述
        out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=sum,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })
@goods_blue.route("/callback")
def callback():
    try:
        sql = "update orders set status=3"
        db.add(sql)
        db.commit()
    except:
        db.rollback()
    # 跳转到个人中心
    return redirect('http://localhost:8080/#/')